<template>
  <div class="statio">
    <div class="serch">
      <el-button type="primary" @click="addRoles(0)" plain="plain" v-if="menuFlag == '23'" class="addRoles"
        size="small">添加角色</el-button>
      <el-button type="primary" @click="addAttributes(0)" plain="plain" v-if="menuFlag == '25'" class="addAttr"
        size="small">添加属性</el-button>
      <el-button type="primary" @click="handleAddLevel" plain="plain" v-if="menuFlag == '36'" class="addAttr"
        size="small">添加一级</el-button>
      <!--<el-button type="primary" @click="addClassType" plain="plain" v-if="menuFlag=='14'" class="addAttr">添加类型</el-button>-->
    </div>
    <div :class="menuFlag == 24 ? 'table-box' : ''">
      <div class="tablebox-l" v-if="menuFlag == 24">
        <el-tabs tab-position="left" @tab-click="handleClicktab" v-model="activeName">
          <el-tab-pane label="全部角色" name="first"></el-tab-pane>
          <el-tab-pane v-for="(item, index) in dictOptions" :key="index" :label="item.name"
            :name="item.name"></el-tab-pane>
        </el-tabs>
      </div>
      <div :class="menuFlag == 24 ? 'tablebox-r' : 'tablebox-r1'">
        <div v-if="menuFlag == '24'">
          <el-row>
            <el-col :span="6" style="margin-right: 20px"><el-input placeholder="请输入姓名" v-model="keyword" clearable>
              </el-input></el-col>
            <el-col :span="4">
              <el-select v-model="enabled" placeholder="请选择账号状态" @change="handleClickselect">
                <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
                </el-option> </el-select></el-col>
            <el-col :span="4">
              <el-button type="primary" @click="handleInquire" plain="plain" class="addAttr">查询</el-button></el-col>
          </el-row>
        </div>
        <base-table v-if="menuFlag != 2 && menuFlag != 36" ref="baseTable" :tableSetting="tableSetting"
          @handleCommon="handleCommon"></base-table>
      </div>
    </div>

    <!-- 表、列表 -->
    <div class="tab-wrap" v-if="menuFlag == 36">
      <el-table :data="tabledata" style="margin-bottom: 20px" row-key="id" tooltip-effect="dark"
        :header-cell-style="{ background: '#F9F9F9' }" border default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <!-- <el-table-column type="index" label="序号" width="80">
          <template slot-scope="scope">
            <span>{{ scope.row.index }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="name" label="目录树" align="center"></el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="success" plain v-if="scope.row.index < 3" @click="handlenewtwolabel(scope.row)">添加子级</el-button>
            <!-- v-if="scope.row.pid == 0 || scope.row.pid == 1" -->
            <el-button size="mini" type="info" plain @click="handleeditbutton(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" plain @click="handledeletebutton(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 添加-修改弹框 -->
    <el-dialog :title="titleStation" :close-on-click-modal="false" :show-close="false" :visible.sync="dialogStation"
      width="500px" center>
      <el-form status-icon label-width="120px" :model="form" :rules="rules" ref="form" class="demo-ruleForm">
        <el-form-item label="角色名称" prop="name" v-if="static == 0 || static == 1">
          <el-input v-model.trim="form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="属性名称" prop="name" v-if="static == 2 || static == 3">
          <el-input v-model.trim="form.name" placeholder="请输入属性名称"></el-input>
        </el-form-item>
        <el-form-item label="类型名称" prop="name" v-if="static == 4 || static == 5 || static == 6 || static == 7">
          <el-input v-model.trim="form.name" placeholder="请输入类型名称"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="close('form')">取消</el-button>
        <el-button type="primary" @click="save('form')" :loading="loading">确定</el-button>
      </span>
    </el-dialog>
    <!-- 权限设置 -->
    <el-dialog title="权限设置" :close-on-click-modal="false" :show-close="false" :visible.sync="dialogTree" width="500px"
      center>
      <!-- :default-checked-keys="checkTree" -->
      <el-tree :data="propertyList" show-checkbox node-key="id" :props="defaultProps" default-expand-all
        ref="tree"></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogTree = false">取 消</el-button>
        <el-button type="primary" @click="beture" :loading="loading">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改账号 -->
    <el-dialog title="编辑账号" :close-on-click-modal="false" :show-close="false" :visible.sync="dialogRode" width="500px"
      center>
      <el-form status-icon label-width="120px" :model="form" :rules="ruless" ref="form" class="demo-ruleForm">
        <el-form-item label="账号" prop="userName">
          <el-input v-model.trim="form.userName" placeholder="请输入账号"></el-input>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model.trim="form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model.trim="form.phone" placeholder="请输入手机号"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="roleId">
          <el-select class="filter-item" v-model.trim="form.roleId" placeholder="请选择岗位">
            <el-option v-for="attr in dictOptions" :key="attr.code" :label="attr.name" :value="attr.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogRode = false">取消</el-button>
        <el-button type="primary" @click="saveRode('form')" :loading="loading">确定</el-button>
      </span>
    </el-dialog>

    <!-- 添加、编辑目录弹框 -->
    <el-dialog :title="title" :visible.sync="editlabeldialog" :close-on-press-escape="false" :close-on-click-modal="false"
      :show-close="false" width="35%">
      <el-form :model="ediForm" ref="ediForm">
        <el-form-item label="目录名称" :label-width="formLabelWidth" prop="ediname" :rules="[
          { required: true, message: '目录名称不能为空', trigger: 'blur' },
        ]">
          <el-input v-model="ediForm.ediname" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editlabeldialog = false">取 消</el-button>
        <el-button type="primary" @click="handleeditlabel('ediForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getdeptList } from "@/service/Api";
import baseTable from "@/components/table/baseTable";
import menuleft from "@/components/menuItem/menuleft.vue";
import {
  getAuthRoleList,
  accountManagList,
  attributeList,
  addRole,
  updateRole,
  getResourceList,
  deleteRole,
  resetPassword,
  updateAccount,
  insertAttribute,
  disableUser,
  updateAttribute,
  deleteAttribute,
  getAllSecondAuthResourceList,
  addRoleResource,
  selectProjectPlate,
  insertProjectPlate,
  postaddDept,
  deletaDeleteDept,
  puteditDept,
} from "@/service/Api.js"; //接口

import bus from "../../../components/bus";

export default {
  components: { baseTable, menuleft },
  name: "systemMent",
  props: ["menuFlag"],
  data() {
    return {
      tableSetting: {
        tableApiFn: getAuthRoleList,
        options: [{ prop: "name", label: "角色名称" }],
        btns: [
          {
            text: "权限设置",
            size: "mini",
            handleName: "btnTree",
            type: "success",
            plain: "plain",
          },
          {
            text: "编辑",
            size: "mini",
            handleName: "addRoles",
            type: "primary",
            plain: "plain",
          },
          {
            text: "删除",
            size: "mini",
            handleName: "btndeleteRole",
            type: "danger",
            plain: "plain",
          },
        ],
      },
      //角色
      dialogStation: false,
      titleStation: "",
      loading: false,
      form: { name: "", userName: "", roleId: "" },
      rules: {
        name: [
          {
            required: true,
            message: "请输入内容",
            trigger: "blur",
          },
        ],
      },
      static: "",
      id: "",
      roleId: "",
      //权限
      formTree: { name: "" },
      dialogTree: false,
      propertyList: [],
      defaultProps: { children: "children", label: "name" },
      checkTree: [],
      //账号
      dialogRode: false,
      dictOptions: [],
      ruless: {
        name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
        userName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
        ],
        roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
      },

      tabledata: [], //组织结构配置
      editlabeldialog: false,
      ediForm: { ediname: "" },
      formLabelWidth: "120px",
      title: "",
      pid: 0,
      branchId: 0,
      options: [
        {
          value: "",
          label: "全部状态",
        },
        {
          value: "1",
          label: "正常",
        },
        {
          value: "2",
          label: "禁用",
        },
      ],
      roleId: "",
      enabled: "",
      keyword: "",
      activeName: "first",
    };
  },
  watch: {
    //根据菜单显示列表信息
    menuFlag(val) {
      if (val == "23") {
        this.tableSetting = {
          tableApiFn: getAuthRoleList,
          defaulteParams: {
            keyword: this.keyword,
          },
          options: [{ prop: "name", label: "角色名称" }],
          btns: [
            {
              text: "权限设置",
              size: "mini",
              handleName: "btnTree",
              type: "success",
              plain: "plain",
            },
            {
              text: "编辑",
              size: "mini",
              handleName: "addRoles",
              type: "primary",
              plain: "plain",
            },
            {
              text: "删除",
              size: "mini",
              handleName: "btndeleteRole",
              type: "danger",
              plain: "plain",
            },
          ],
        };
      } else if (val == "24") {
        this.tableSetting = {
          tableApiFn: accountManagList,
          defaulteParams: {
            keyword: this.keyword,
            enabled: this.enabled,
            roleId: this.roleId,
          },
          width: "300",
          options: [
            { prop: "userName", label: "账号" },
            { prop: "name", label: "姓名" },
            { prop: "roleName", label: "角色" },
            { prop: "enabled", label: "账号状态" },
          ],
          btns: [
            {
              text: "重置密码",
              size: "mini",
              handleName: "btnResetpwd",
              type: "success",
              plain: "plain",
            },
            {
              text: "编辑",
              size: "mini",
              handleName: "btnUpdateuser",
              type: "primary",
              plain: "plain",
            },
            {
              text: "禁用",
              size: "mini",
              handleName: "btnDisableuser",
              type: "danger",
              plain: "plain",
              show: (row) => {
                return row.enabled == 1;
              },
            },
            {
              text: "启用",
              size: "mini",
              handleName: "btnDisableuser",
              type: "success",
              plain: "plain",
              show: (row) => {
                return row.enabled == 2;
              },
            },
          ],
        };
      } else if (val == "25") {
        this.tableSetting = {
          tableApiFn: attributeList,
          defaulteParams: {
            keyword: this.keyword,
          },
          options: [{ prop: "name", label: "属性名称" }],
          btns: [
            {
              text: "编辑",
              size: "mini",
              handleName: "addAttributes",
              type: "primary",
              plain: "plain",
            },
            {
              text: "删除",
              size: "mini",
              handleName: "btnDeleteatt",
              type: "danger",
              plain: "plain",
            },
          ],
        };
      }
      if (val == "36") {
        this.getdept();
      } else {
        // this.$nextTick(() => {
        //   this.$refs.baseTable.initData();
        // });
        setTimeout(() => {
          this.$refs.baseTable.initData();
        }, 10);
      }
      // setTimeout(() => {
      //   this.$refs.baseTable.initData();
      // }, 10);
    },
  },
  created() {
    this.getRoleList();
  },
  methods: {
    handleCommon(name, row, idx) {
      if (this[name]) {
        this[name](row, idx);
      }
    },

    // 点击切换部门tab
    handleClicktab(tab, event) {
      this.activeName = tab.name;
      console.log("activeName", tab.name, event);
      this.dictOptions.forEach((el) => {
        if (tab.name === el.name) {
          // return el.id;
          this.roleId = el.id;
          console.log("id", el.id);
        }
      });
      if (this.activeName != "first") {
        this.tableSetting.defaulteParams.roleId = this.roleId;
      } else {
        this.roleId = "";
        this.tableSetting.defaulteParams.roleId = "";
      }

      // console.log("id", rolebox);
      this.$nextTick(() => {
        this.$refs.baseTable.initData();
      });
    },
    // 选择禁用状态
    handleClickselect(value) {
      this.enabled = value;
    },
    // 查询
    handleInquire() {
      this.tableSetting.defaulteParams = {
        keyword: this.keyword,
        enabled: this.enabled,
        roleId: this.roleId,
      };
      this.$nextTick(() => {
        this.$refs.baseTable.initData();
      });
    },
    //关闭弹框
    close(formName) {
      this.$refs[formName].resetFields();
      this.dialogStation = false;
    },
    //添加-修改角色
    addRoles(row) {
      if (row == 0) {
        this.titleStation = "添加角色";
        this.static = 0;
        this.id = "";
        this.form.name = "";
      } else {
        this.titleStation = "修改角色";
        this.static = 1;
        this.id = row.id;
        this.form.name = row.name;
      }
      this.dialogStation = true;
    },
    //确认添加-修改
    save(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          let data = {
            id: this.id,
            name: this.form.name,
          };
          this.static == 0
            ? (url = addRole(data))
            : this.static == 1
              ? (url = updateRole(data))
              : this.static == 2
                ? (url = insertAttribute(data))
                : (url = updateAttribute(data));
          url.then((res) => {
            if (res.code == 0) {
              this.$message.success("操作成功!");
              this.$refs.baseTable.initData();
              this.close("form");
            }
          });
        } else {
          return false;
        }
      });
    },
    //权限设置
    btnTree(row) {
      this.id = row.id;
      this.roleId = row.id;
      getResourceList().then((res) => {
        if (res.code == 0) {
          console.log("权限设置", res);
          this.propertyList = res.data;
          this.checkPerone(this.roleId);
        }
      });
      this.dialogTree = true;
    },
    //权限回显
    checkPerone(roleId) {
      getAllSecondAuthResourceList(roleId).then((res) => {
        if (res.code == 0) {
          if (res.data.length > 0) {
            let arr = [];
            res.data.forEach((element) => {
              arr.push(element.id);
            });
            this.$refs.tree.setCheckedKeys(arr);
          } else {
            this.$refs.tree.setCheckedKeys([]);
          }
        }
      });
    },
    beture() {
      let bytesList = this.$refs.tree.getCheckedKeys();
      let fatherList = this.$refs.tree.getHalfCheckedKeys();
      let keyList = [...fatherList, ...bytesList];
      console.log(fatherList);
      addRoleResource(this.roleId, keyList).then((res) => {
        if (res.code == 0) {
          this.$message.success("操作成功~");
          bus.$emit("setRole");
          this.dialogTree = false;
        }
      });
    },
    //删除角色
    btndeleteRole(row) {
      this.$confirm("此操作将永久删除,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      }).then(() => {
        let reo;
        reo = deleteRole(row.id);
        reo.then((res) => {
          if (res.code == 0) {
            this.$message.success("删除成功!");
            this.$refs.baseTable.initData();
          } else {
            this.$message.warning("当前角色还有账号在使用，请勿删除~!");
            this.$refs.baseTable.initData();
          }
        });
      });
    },
    //重置密码
    btnResetpwd(row) {
      this.$confirm("是否重置密码?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          resetPassword(row.id);
          this.$refs.baseTable.initData();
          this.$message.success("重置成功!");
          this.$refs.baseTable.initData();
        })
        .catch(() => {
          // this.$message.info("已取消!");
        });
    },
    //账号修改
    btnUpdateuser(row) {
      this.fousdep();
      this.id = row.id;
      this.form.name = row.name;
      this.form.userName = row.userName;
      this.form.roleId = row.roleId;
      this.form.phone = row.phone;
      this.dialogRode = true;
    },
    //确定修改
    saveRode(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url;
          let data = {
            id: this.id,
            roleId: this.form.roleId,
            name: this.form.name,
            userName: this.form.userName,
            phone: this.form.phone,
          };
          url = updateAccount(data);
          url.then((res) => {
            if (res.code == 0) {
              this.$message.success("操作成功!");
              this.dialogRode = false;
              this.$refs.baseTable.initData();
            } else {
              this.$message.error("操作异常!");
            }
          });
        } else {
          return false;
        }
      });
    },
    //角色下拉
    fousdep() {
      let data = {};
      this.getRoleList();
    },

    // 角色列表
    getRoleList() {
      getAuthRoleList().then((res) => {
        this.dictOptions = res.data;
      });
    },
    //账号禁用
    btnDisableuser(row) {
      let text, enableType;
      if (row.enabled == 1) {
        text = "禁用";
        enableType = 2;
      } else {
        text = "启用";
        enableType = 1;
      }
      this.$confirm(`此操作将${text}账号,是否继续?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          disableUser(row.id, enableType).then(
            (result) => {
              if (result.code == 0) {
                this.$message.success(`${text}成功!`);
                this.$refs.baseTable.initData();
              } else {
                this.$message.warning(result.message);
              }
            },
            (err) => {
              this.$message.error("服务器错误~");
            }
          );
        })
        .catch(() => { });
    },
    //添加-修改属性
    addAttributes(row) {
      if (row == 0) {
        this.titleStation = "添加属性";
        this.static = 2;
        this.id = "";
        this.form.name = "";
      } else {
        this.titleStation = "修改属性";
        this.static = 3;
        this.id = row.id;
        this.form.name = row.name;
      }
      this.dialogStation = true;
    },
    //删除属性
    btnDeleteatt(row) {
      this.$confirm("此操作将永久删除,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          deleteAttribute(row.id);
          this.$refs.baseTable.initData();
          this.$message.success("删除成功!");
          this.$refs.baseTable.initData();
        })
        .catch(() => {
          //    this.$message.info("已取消!");
        });
    },
    // 部门列表
    getdept(data) {
      // getdeptList().then((res) => {
      //   if (res.code === 0) {
      //     this.tabledata = res.data;
      //   }
      // });
      // 获取后台树形数据列表
      getdeptList(data).then((res) => {
        this.tabledata = res.data;
        // 判断树形数据不为空，执行方法
        if (this.tabledata.length > 0) this.setTableIndex(this.tabledata);
      });
    },
    // 树形列表index层级，实现方法（可复制直接调用）
    setTableIndex(arr, index) {
      arr.forEach((item, key) => {
        item.index = 1;
        if (index) {
          item.index = index + 1;
        }
        if (item.children) {
          this.setTableIndex(item.children, item.index);
        }
      });
    },
    // 添加一级组织结构
    handleAddLevel() {
      this.title = "添加一级结构";
      this.pid = 0;
      this.ediForm.ediname = "";
      this.editlabeldialog = true;
    },
    // 添加二级组织结构
    handlenewtwolabel(row) {
      this.title = "添加二级结构";
      this.pid = row.id;
      this.ediForm.ediname = "";
      this.editlabeldialog = true;
      console.log(row);
    },
    //编辑
    handleeditbutton(row) {
      this.title = row.pid === 0 ? "编辑一级结构" : "编辑二级结构";
      this.branchId = row.id;
      this.ediForm.ediname = row.name;
      this.editlabeldialog = true;
    },
    // 刪除
    handledeletebutton(row) {
      console.log(22222, row.id);
      this.$confirm("此操作将永久删除该目录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          deletaDeleteDept(row.id).then((res) => {
            if (res.code === 0) {
              this.$message.success("删除成功");
              this.editlabeldialog = false;
              this.getdept();
            } else {
              this.$message.error(`${res.message}`);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //编辑标签点击确定
    handleeditlabel(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.title === "添加一级结构" || this.title === "添加二级结构") {
            postaddDept({ name: this.ediForm.ediname, pid: this.pid })
              .then((res) => {
                if (res.code === 0) {
                  this.$message.success("添加成功");
                  this.getdept();
                }
              })
              .catch((err) => {
                console.log(err);
              });
          } else if (
            this.title === "编辑一级结构" ||
            this.title === "编辑二级结构"
          ) {
            puteditDept({ name: this.ediForm.ediname, id: this.branchId })
              .then((res) => {
                if (res.code === 0) {
                  this.$message.success("编辑成功");
                  this.getdept();
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }
          this.editlabeldialog = false;
          // this.$nextTick(() => {
          //   this.getdept();
          // });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    addClassType(row = null) {
      this.$prompt("请输入类型名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValidator: this.validator,
        inputValue: row ? row.name : "",
      })
        .then(({ value }) => {
          row ? this.addClass(value) : this.exitClass();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入",
          });
        });
    },
    addClass(name) {
      insertProjectPlate({
        name,
      }).then((res) => {
        if (res.code === 0) {
          this.$message.success("添加成功");
          this.$refs.baseTable.initData();
        }
      });
    },
    exitClass(name) { },
    removeClass() { },

    validator(val) {
      if (val) return true;
      else return "请输入内容";
    },
  },
};
</script>

<style scoped>
.search span {
  display: flex;
  justify-content: space-between;
}

.addRoles,
.addAttr {
  margin-bottom: 15px;
}

.table-box {
  display: flex;
}

.tablebox-r {
  width: 88%;
  margin-left: 20px;
}

.tablebox-r1 {
  width: 100%;
}
</style>
